package multitionPattern;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 带生命周期的多例模式
 */
public class LifecycleMultiton {
    private static final Map<String, LifecycleMultiton> instances = new ConcurrentHashMap<>();
    private static final long MAX_AGE_MS = 30 * 60 * 1000; // 30分钟
    
    private final String key;
    private final long creationTime;
    private long lastAccessTime;
    
    private LifecycleMultiton(String key) {
        this.key = key;
        this.creationTime = System.currentTimeMillis();
        this.lastAccessTime = this.creationTime;
    }
    
    public static synchronized LifecycleMultiton getInstance(String key) {
        cleanupExpiredInstances();
        
        LifecycleMultiton instance = instances.get(key);
        if (instance == null) {
            instance = new LifecycleMultiton(key);
            instances.put(key, instance);
        }
        
        instance.lastAccessTime = System.currentTimeMillis();
        return instance;
    }
    
    private static void cleanupExpiredInstances() {
        long currentTime = System.currentTimeMillis();
        instances.entrySet().removeIf(entry -> {
            LifecycleMultiton instance = entry.getValue();
            boolean expired = (currentTime - instance.lastAccessTime) > MAX_AGE_MS;
            if (expired) {
                System.out.println("清理过期实例: " + instance.key);
            }
            return expired;
        });
    }
    
    public String getKey() {
        return key;
    }
    
    public long getAge() {
        return System.currentTimeMillis() - creationTime;
    }
    
    public long getIdleTime() {
        return System.currentTimeMillis() - lastAccessTime;
    }
    
    public static int getActiveInstanceCount() {
        return instances.size();
    }
}